package com.crm.services;

import java.util.List;
import java.util.Map;

import javax.imageio.spi.IIOServiceProvider;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.model.jdao.ICustomerDAO;
import com.crm.model.jdao.IDictionaryDAO;
import com.crm.model.mdao.CustomerMapper;
import com.crm.model.mdao.GatherguestsMapper;
import com.crm.model.mpojo.Gatherguests;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.Dictionary;
import com.crm.model.pojo.SalesOpportunity;
import com.crm.util.LoginUtil;
import com.github.pagehelper.PageHelper;

/**
 * 客户服务类
 * 
 * @author Menghui
 *
 */
@Service
public class CustomerServices {

	@Autowired
	ICustomerDAO custDAO;// 客户dao
	@Autowired
	IDictionaryDAO dictDAO;// 字典dao
	@Autowired
	CustomerMapper cMapper;// 客户mybatisDAO
	@Autowired
	private DictionaryServices ds;// 字典表服务类
	@Autowired
	private GatherguestsMapper gaMapper;//获客mybatisDAO
	@Autowired
	private OrderInfoServers ois;//订单服务类

	/**
	 * mybatis查询所有客户信息
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @return
	 * @throws ServiceException
	 */
	public List<Map<String, String>> selectByPager(int pageNum, int pageSize) throws ServiceException {
		// 使用分页插件
		System.out.println("pageNum:" + pageNum + ",pageSize:" + pageSize);
		// 配置分页信息
		PageHelper.startPage(pageNum, pageSize);
		if(LoginUtil.getUser()!=null) {
			List<Map<String, String>> selectAllCustomer = cMapper.selectAllCustomer(LoginUtil.getUser().getuId(), LoginUtil.getUser().getuDept());
			System.out.println("权限客户："+selectAllCustomer);
			return selectAllCustomer;
		}
		return null;
	}
	
	/**
	 * 查询客户姓名
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public List<Map<String, String>> selectCustName() {
		return cMapper.selectCustName();
	}
	
	//客户种类
	public List<Map<String, String>> selectCustType(int pageNum, int pageSize,
			Integer custType) {
		PageHelper.startPage(pageNum, pageSize);
		System.out.println("客户种类分页："+pageNum+","+pageSize);
		return cMapper.selectByctype(custType);
	}
	
	//客户类型
	public List<Map<String, String>> selectCustSort(int pageNum, int pageSize,
			Integer custSort) {
		PageHelper.startPage(pageNum, pageSize);
		System.out.println("客户类型分页："+pageNum+","+pageSize);
		return cMapper.selectBycsort(custSort);
	}
	
	//客户来源
	public List<Map<String, String>> selectCustSource(int pageNum, int pageSize,
			Integer custSource) {
		PageHelper.startPage(pageNum, pageSize);
		System.out.println("客户来源分页："+pageNum+","+pageSize);
		return cMapper.selectBycsource(custSource);
	}
	
	//客户姓名模糊查询
	public List<Map<String, String>> selectCNameLike(int pageNum, int pageSize,
			String custName) {
		PageHelper.startPage(pageNum, pageSize);
		System.out.println("模糊查询客户姓名分页："+pageNum+","+pageSize);
		return cMapper.selectBycustName(custName);
	}
	
	//全部客户
	public List<Map<String, String>> selectCustomerAll(int pageNum, int pageSize,
			Integer customer) {
		PageHelper.startPage(pageNum, pageSize);
		System.out.println("全部客户分页："+pageNum+","+pageSize);
		return cMapper.selectAllCustomer2();
	}
	
	public List<Map<String, String>> selectCustomerAll2(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		System.out.println("全部客户分页："+pageNum+","+pageSize);
		return cMapper.selectAllCustomer2();
	}

	/**
	 * 查询所有客户信息，用于前台数据筛选
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @return
	 * @throws ServiceException
	 */
	public List<Map<String, String>> selectAllCustomer() throws ServiceException {
		return cMapper.selectAllCustomer2();
	}
	
	public Customer findByCustName(String custName) {
		return custDAO.findByCustName(custName);
	}

	/**
	 * 使用jpa分页查询
	 * 
	 * @return
	 */
	public List<Customer> findAll() {
		//这里要写成带条件的分页！！！！！！！！！！！！，1206表示启用，1207表示禁用	
		Pageable pageable =PageRequest.of(0,5);	
		//查询条件构造
		 Specification<Customer> spec=new Specification<Customer>(){

			@Override
			public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				Predicate p=cb.equal(root.get("status").as(Integer.class), 1206);
				return p;
			}
			 
		 };
		Page<Customer> page =custDAO.findAll(spec,pageable);
		return page.getContent();

	}

	/**
	 * 模糊查询
	 * 
	 * @param custName
	 * @return
	 */
	public List<Customer> findByCustNameLike(String custName) {
		return custDAO.findByCustNameLike(custName);

	}
	
	/**
	 * id查询
	 * @param custId
	 * @return
	 */
	public Customer findByCustID(Integer custId) {
		return custDAO.findByCustId(custId);
		
	}
	/**
	 * 将list的数据转换成JsonArray的数据
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray(List<Customer> list) {
		JSONArray array = new JSONArray();
		for (Customer customer : list) {
			// System.out.println("salesOpportunity:"+salesOpportunity);
			String conName = customer.getContact().getConName();
			Integer conId = customer.getContact().getConId();
			String phone=customer.getContact().getCustTel();
			System.out.println("customer:" + customer.getCustName() + ";conName:" + customer.getContact().getConName());
			JSONObject obj = new JSONObject();
			obj.put("value", customer.getCustName());
			obj.put("label1", customer.getCustId());
			if (" ".equals(conName) || conName == null) {
				conName = " ";
				conId = 0;
			}
			obj.put("conName", conName);
			obj.put("tel", phone);
			obj.put("label2", conId);
			array.add(obj);
		}
		return array;
	}
	
	/**
	 * 将list的数据转换成JsonArray的数据
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray1(Customer customer) {
		JSONArray array = new JSONArray();
			List<SalesOpportunity> sales=customer.getSalesOpportunities();
			for (SalesOpportunity sale : sales) {
				JSONObject obj=new JSONObject();
				obj.put("value", sale.getSalId());
				obj.put("label", sale.getSalTheme());
				System.out.println("name:"+sale.getSalTheme()+"\t"+"id:"+sale.getSalId());		
				System.out.println(obj.toString());
				array.add(obj);
			}

		return array;
	}
	
	/**
	 * 查询全部字典表信息
	 * 
	 * @return
	 */
	public List<Dictionary> findAllDict() {
		List<Dictionary> dictList = dictDAO.findAllDict();
		return dictList;
	}

	/**
	 * 添加客户
	 * 
	 * @param cust
	 * @return
	 */
	public void insertCust() {
		Customer customer = new Customer();
		custDAO.save(customer);
	}
	
	/**
	 * 获客信息
	 * 
	 * @param customer
	 * @return
	 */
	public Customer addCust(Customer customer) {
		//boolean flag = false;
		Customer newCustomer = custDAO.save(customer);
		if (newCustomer != null) {
			System.out.println("获客信息：" + newCustomer);
		}
		System.out.println("新增一条客户信息：" + customer);
		return newCustomer;
	}

	/**
	 * 客户转JSONObject
	 * 
	 * @param obj
	 * @param customer
	 * @return
	 */
	public JSONObject tojsonObject1(JSONObject obj, Customer customer) {
		obj.put("custId", customer.getCustId());
		obj.put("addTime", customer.getAddTime());
		obj.put("checkout", customer.getCheckout());
		obj.put("creditRating", customer.getCreditRating());
		obj.put("custAddress", customer.getCustAddress());
		obj.put("custArea", customer.getCustArea());
		obj.put("custEmail", customer.getCustEmail());
		obj.put("custName", customer.getCustName());
		obj.put("custSex", customer.getCustSex());
		obj.put("custShortname", customer.getCustShortname());
		obj.put("custSort", customer.getCustSort());
		obj.put("custSource", customer.getCustSource());
		obj.put("custStage", customer.getCustStage());
		obj.put("custTel", customer.getCustTel());
		obj.put("custType", customer.getCustType());
		obj.put("firstSigning", customer.getFirstSigning());
		obj.put("industry", customer.getIndustry());
		obj.put("relationLevel", customer.getRelationLevel());
		obj.put("remarks", customer.getRemarks());
		obj.put("superiorClient", customer.getSuperiorClient());
		return obj;
	}
	
	//根据id查询客户
	public Map<String, String> findByCustId(Integer custId) {
		return cMapper.selectById(custId);
	}
	
	public Customer selectCustId(Integer custId) {
		return custDAO.findByCustId(custId);
	}

	// 删除客户
	public Object deleteCustomer(Integer custId) {
		return cMapper.deleteCustomer(custId);
	}
	/**
	 * 根据ID查询客户用于前台数据筛选
	 * @param custId
	 * @return
	 */
	public Customer findByCustIdPage(Integer custId) {
		return custDAO.findById(custId).get();
	}
	
	/**
	 * 查询所有客户名称
	 * @return 
	 */
	/*public List<String> selectAllCustomerName() {
		return cMapper.selectAllCustomer();
	}*/
	
	/**
	 * 根据客户编号查询联系人
	 * @param custid
	 * @return
	 */
	public String selectcustTocon(Integer custid) {
		return custDAO.findByCustId(custid).getContact().getConName();
	}	
	//修改客户信息
	public Object updateCustomer(Customer customer) {
		return cMapper.updateCustomer(customer);
	}
	
	//单个转移
	public int updateClient2(Integer client,Integer idss) {
		System.out.println("客户id"+idss);
		return cMapper.updateClient2(client, idss);
	}
	
	//转公海
	public int updateSea(Integer custId) {
		//修改为公海客户
		return cMapper.updateSea(custId);
	}
	
	//转普通
	public int updateTransfer(Integer custId) {
		//修改为普通客户
		return cMapper.updateTransfer(custId);
	}
	
	//智能合并
	public List<Customer> IntellMerger() {
		System.out.println("这里是客户智能合并");
		List<Customer> intel = cMapper.IntellMerger();
		System.out.println("查询到的客户有："+intel);
		for(int i=1;i<intel.size()-1;i++) {
			//第一个值
			Customer c1 = intel.get(i);
			System.out.println("kehu:"+c1);
			//第二个值
			Customer c2 = intel.get(i+1);
			System.out.println("kehu222:"+c2);
			if(c1.getCustEmail().equals(c2.getCustEmail()) || c1.getCustTel().equals(c2.getCustTel())) {
				System.out.println("第一个客户："+c1.getCustEmail()+"客户id："+c1.getCustId());
				System.out.println("第二个客户："+c2.getCustEmail()+"客户id："+c2.getCustId());
				//查询订单未完成的客户
				List<Map<String, String>> selelctCustid = ois.selelctCustid(c1.getCustId());
				if(null == selelctCustid || selelctCustid.size() ==0) {
					if(c2.getCheckout()==null) {
						c2.setCheckout(c1.getCheckout());
					}
					if (c2.getCreditRating()==null) {
						c2.setCreditRating(c1.getCreditRating());
					}
					if (c2.getCustAddress()==null) {
						c2.setCustAddress(c1.getCustAddress());
					}
					if (c2.getCustArea()==null) {
						c2.setCustArea(c1.getCustArea());
					}
					if (c2.getCustName()==null) {
						c2.setCustName(c1.getCustName());
					}
					if (c2.getCustSex()==null) {
						c2.setCustSex(c1.getCustSex());
					}
					if (c2.getCustShortname()==null) {
						c2.setCustShortname(c1.getCustShortname());
					}
					if (c2.getCustSort()==null) {
						c2.setCustSort(c1.getCustSort());
					}
					if (c2.getCustSource()==null) {
						c2.setCustSource(c1.getCustSource());
					}
					if (c2.getCustStage()==null) {
						c2.setCustStage(c1.getCustSource());
					}
					if (c2.getCustType()==null) {
						c2.setCustType(c1.getCustType());
					}
					if (c2.getFirstSigning()==null) {
						c2.setFirstSigning(c1.getFirstSigning());
					}
					if (c2.getIndustry()==null) {
						c2.setIndustry(c1.getIndustry());
					}
					if (c2.getRelationLevel()==null) {
						c2.setRelationLevel(c1.getRelationLevel());
					}
					if (c2.getRemarks()==null) {
						c2.setRemarks(c1.getRemarks());
					}
					if (c2.getSuperiorClient()==null) {
						c2.setSuperiorClient(c1.getSuperiorClient());
					}
				}else {
					System.out.println("合并不成功！");
				}
				int updateCustomer = cMapper.updateCustomer(c2);//执行修改
				System.out.println("修改客户信息是否成功为1******："+updateCustomer);
				int deleteCustomer = cMapper.deleteCustomer(c1.getCustId());
				System.out.println("逻辑删除客户是否成功为1******："+deleteCustomer);
			}
		}
		return intel;
	}

}
